function [Y,flag,schema]=quant_transf(X)
 
flag=0;
ay=abs(X);
sy=sign(X);
% Scale 
A=ay(:);
A=A(A~=0);  % set of values
a=hist(A,1:max(A));
scale=find(a~=0);
if isempty(scale)
Y=zeros(size(X));
schema=0; 
return;
end; 
Q=length(scale);
S=word2bin(scale);
S=fliplr(sum(S));
% number of starting zeros
i=0;
while S(i+1)==0, i=i+1; end;

%if S(i+1)==1 
%    schema(1)=1; % special a1
%    if S(i+2)==Q, schema(2)=i+2;
%    else schema(2)=i+1; end;
%else
%    schema(1)=0;
%    if S(i+1)==Q, schema(2)=i+1;
%    else
%        schema(2)=i;
%        schema(1)=2;
%    end;
%end

%step=2^schema(2);
%schema(2)=i;

% test for scale
%if schema(1)~=2
%    d=floor(step/2);
%else
%    d=0;
%end;

%qscale=(scale-d)/step;      % quantiization indices
%if schema(1)==1, 
%    qscale(1)=1;
%    qscale(2:Q)=qscale(2:Q)+1;
%end;
% reconstruction

    
%if schema(1)==1,
%    rscale(2:Q)=(qscale(2:Q)-1)*step+d;
%    rscale(1)=step/4*3; 
%else
%    rscale=qscale*step+d;
%end;
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
if S(i+1)==1 
    schema(1)=1; % special a1
    if S(i+2)==Q, 
        schema(2)=i+2;
    else
        schema(2)=i+1;
        schema(1)=3;
    end;
else
    schema(1)=0;
    if S(i+1)==Q, schema(2)=i+1;
    else
        schema(2)=i;
        schema(1)=2;
    end;
end

step=2^schema(2);
schema(2)=i;

% test for scale
% compression
if schema(1)==0 || schema(1)==1
    d=floor(step/2);
else
    d=0;
end;

qscale=(scale-d)/step;      % quantiization indices
if schema(1)==1 ||schema(1)==3  , 
    qscale(1)=1;
    qscale(2:Q)=qscale(2:Q)+1;
end;
% reconstruction

    
if schema(1)==1 || schema(1)==3,
    rscale(2:Q)=(qscale(2:Q)-1)*step+d;
    rscale(1)=step/4*3; 
else
    rscale=qscale*step+d;
end;
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

% compression
Y=X;
for i=1:Q 
    F=ay==scale(i);
    Y(F)=qscale(i);
end;

Y=Y.*sy;
%bits(2)=online(Y(:));


% reconstruction
RY=zeros(size(Y));
for i=1:Q 
    F=abs(Y)==qscale(i);
    RY(F)=rscale(i);
end;
RY=RY.*sy;

% CHECK if no errors
if ~all(RY==X), disp('ERROR'); flag=1; end; 

% 
function y=word2bin(x,l)
% x is integer vector,
% y is its binary representation
% l is length of binary vector
if nargin==1,
    l=ceil(log2(max(x)+1));
end;
[m,n]=size(x);
if m<n, x=x'; m=n; end;  
y=zeros(m,l);
L=l;
while sum(x)>0,
  y(:,L)=mod(x,2);
  x=floor(x/2);
  L=L-1;
end;




